﻿using System.Text;
using System.Web;
using System.Web.Mvc;
using tour.szhome.common;
using TOUR.SZHOME.Attributes;
using TOUR.SZHOME.BLL;
using TOUR.SZHOME.Entity;

namespace tour.szhome.manage.area.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        LoginBLL _loginbll = new LoginBLL();

        public ActionResult Index(string returnUrl = "")
        {
            ViewBag.returnUrl = returnUrl;
            return View();
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="username">个性名/用户ID</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public ActionResult Login(string username, string password)
        {
            LoginEntity model = _loginbll.GetModelByName(username); // 先拿到实体
            
            //检测用户是否存在
            if (model != null)
            {
                if (model.userPassword == MD5AndXOREncrypt._Encrypt(password))
                {
                     //写cookie
                    string userInfo = string.Join(",", model.userID.ToString(),HttpUtility.UrlEncode(model.userName, Encoding.GetEncoding("UTF-8")));
                    Authentication.SetAuthCookie(userInfo);
                    return Json(new { code = 0, msg = "登录成功！" });
                }
                return Json(new { code = 1, msg = "密码错误！" });
            }
            return Json(new { code = 2, msg = "用户不存在或不可用！" });
        }

        /// <summary>
        /// 注销登录
        /// </summary>
        /// <returns></returns>
        [SelfOnly]
        public ActionResult LogOut()
        {
            Authentication.SignOut();
            return Json(true);
        }
    }
}
